package com.settlement.system.csv;

import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.converters.AutoConverter;
import com.alibaba.excel.converters.Converter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 头部解析
 * @author user
 */
public class HeadParseUtil {

    private static Map<Class, Headers> cacheHeaders = new ConcurrentHashMap<>();

    public static Headers parse(Class<?> headClass) {

        if (cacheHeaders.containsValue(headClass)) {
            return cacheHeaders.get(headClass);
        }
        return doParse(headClass);
    }

    private static Headers doParse(Class<?> headClass) {
        synchronized (headClass) {

            if (cacheHeaders.containsKey(headClass)) {
                return cacheHeaders.get(headClass);
            }

            Field[] fields = headClass.getDeclaredFields();
            List<Header> headerList = new ArrayList<>();
            for (int index = 0; index < fields.length; index++) {

                ExcelProperty excelProperties = fields[index].getAnnotation(ExcelProperty.class);
                ExcelIgnore excelIgnores = fields[index].getAnnotation(ExcelIgnore.class);
                boolean flag = excelProperties == null
                        || (excelIgnores != null);
                if (flag) {
                    continue;
                }
                Header header = new Header();
                header.setField(fields[index].getName());
                header.setOrder(index);
                String[] values = excelProperties.value();
                if (values != null && values.length >= 1) {
                    header.setTitle(values[0]);
                } else {
                    header.setTitle(fields[index].getName());
                }


                try {
                    Class<? extends Converter> converterClass = excelProperties.converter();
                    if (!converterClass.getName().equals(AutoConverter.class.getName())) {
                        Converter converter = (Converter) converterClass.getConstructors()[0].newInstance();
                        header.setConverter(converter);
                    }
                } catch (Exception ex) {

                }

                headerList.add(header);
            }
            cacheHeaders.put(headClass, new Headers(headerList));
        }
        return cacheHeaders.get(headClass);
    }

}
